package com.donkey.test;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @auther: hemj
 * @since: 2018/7/31
 */
public class ImageCompress {
    public static void main(String[] args) throws IOException {
        String dir = "C:\\Users\\alpha\\Pictures\\";
        String file = "upload_7f84091173fc5a90d305fc38c3c71950.JPG";
        compressPic(dir, dir, file, "out_" + file);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Thumbnails.of(dir + file)
                .scale(1f)
                .outputQuality(0.8f)
                .toOutputStream(baos);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

        FileOutputStream fos = new FileOutputStream(dir + "out.jpg");
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = bais.read(bytes)) > 0) {
            fos.write(bytes);
        }
        fos.close();
        bais.close();
    }

    /**
     * 此方法用于压缩图片，保持原有的高宽
     *
     * @param inputDir       输入图文件夹路径
     * @param outputDir      输出图文件夹路径
     * @param inputFileName  输入图文件名
     * @param outputFileName 输出图文件名
     * @return 返回需要的文件名
     */
    public static String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName) {
        try {
            // 获取源文件，如果源文件小于200KB，不做压缩处理
            File file = new File(inputDir + inputFileName);
            if (file.length() < 1000) {
                return inputFileName;
            }

            Image img = ImageIO.read(file);
            int newWidth = img.getWidth(null);
            int newHeight = img.getHeight(null);
            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(img, 0, 0, null);
            FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            out.close();

            // 压缩完成后，删除源文件
            // file.delete();

        } catch (IOException ex) {
            ex.printStackTrace();
            return inputFileName;
        }
        return outputFileName;
    }

}
